package com.example.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * AES加密
 * @author ..
 * @Date 2023/10/6 11:09
 */
public class AESUtil {
    private static final String AES_ALGORITHM = "AES";
    private static final int AES_KEY_SIZE = 128;

    //加密
    public static String encrypt(String plainText,String key) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM+"/ECB/PKCS7Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    //解密
    public static String decrypt(String encryptedText, String key ) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM+"/ECB/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    //生成密钥
    public static String gainKey(){
        String key ="";
        try {
            // 创建KeyGenerator实例，指定算法为AES
            KeyGenerator keyGenerator = KeyGenerator.getInstance(AES_ALGORITHM);
            // 生成128位的随机密钥
            keyGenerator.init(AES_KEY_SIZE);
            SecretKey secretKey = keyGenerator.generateKey();
            // 密钥转换为字节数组
            byte[] keyBytes = secretKey.getEncoded();
            // 将字节数组转换为Base64字符串，方便存储和传输
            key= Base64.getEncoder().encodeToString(keyBytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return key;
    }
}

class Test{
    public static void main(String[] args) {



        String data = "Hellow 世界!";
        String key = AESUtil.gainKey();
        System.out.println("加密前：");
        System.out.println(data);
        try {
            String encryptedData = AESUtil.encrypt(data, key);
            System.out.println("密文：" + encryptedData);
            String decryptedData = AESUtil.decrypt(encryptedData, key);
            System.out.println("解密后：" + decryptedData);
            System.out.println(data.equals(decryptedData));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
